<?php

class Ftl_ListBO {

    const IMAGE_WIDTH           = 50;
    const IMAGE_HEIGHT          = 50;
    const DATETIME_FORMAT       = 'd/m/Y H:i:s';
    const DATE_FORMAT           = 'd/m/Y';

    private $_numColumns = 0;
    private $_mapOrder  = array();
    private $_io        = null;
    private $_opt       = array(

        'toggleAll'             => false,

        'showActions'           => false,
        'extendedActions'       => array(),
        'canEdit'               => false,
        'canDelete'             => false,
        'canAdd'                => false,
  
        'canOrder'              => true,
        'orderFieldIgnore'      => 'phone',
        'orderBy'               => null,

        'hasStatus'             => true,
        'canChangeStatus'       => false,

        'fields'                => array(),
        'fieldId'               => 'id',
        'encryptFieldId'        => false,
        'fieldStatus'           => 'estado',

        'extendedFilters'		=> array(),
        

        'stateEnabledValue'     => 1,
        'stateDisabledValue'    => -1,
        'stateUnmoderatedValue' => 0,


        'usingPaginator'        => true,
        'resPerPage'            => 50,
        'currentPage'           => 1,
        'totalPages'            => 1,
        'totalResults'          => 1

    );

    
    private $_states = array();
    private $_gender = array(

        'F' => 'Femenino',
        'M' => 'Masculino'

    );

    private $_htmlFilter = "";
    private $_numfilters = 0;
    private $_filtersNames = array();
    private $_jqueryOnLoad = array();
    private $_extendedActions = "";
	private $_extendedFilters = array();

    public function setTotalResults ( $val )
    {
        $this->_opt['totalResults'] = $val;
    }

    public function getCurrentPage ()
    {
        return $this->_opt['currentPage'];
    }

    public function getResPerPage ()
    {
        return $this->_opt['resPerPage'];
    }

    public function getOrderByForSql ()
    {
        $aux = array();

        var_dump($this->_mapOrder);

        foreach ( $this->_mapOrder as $k => $v )
        {
            $aux[] = $k . ' ' . $v;
        }
        
        return implode(',',$aux);
    }
    public function getFilters()
    {
        $res = array();
        if (count($this->_opt['fields']) > 0)
        {
            foreach ($this->_opt['fields'] as $field => $options)
            {

                if ( isset ($options[ 'filter' ] ) && $options[ 'filter' ] )
                {

                    if ( isset($options[ 'type' ]) )
                    {
                        switch ( $options[ 'type' ] )
                        {
                            case 'datetime':
                            case 'date':
                                $res [ $field ] = $this->_io->get($field.'_d') . '|' . $this->_io->get($field.'_h');
                                break;
                            default :
                                $res [ $field ] = $this->_io->get($field);
                                break;
                        }
                    }else {
                        $res [ $field ] = $this->_io->get($field);
                    }
                }
            }

        }
        return $res;
    }
    public function getFiltersForSql()
    {
        $res = array();
        $value = "";
        if (count($this->_opt['fields']) > 0)
        {
            foreach ($this->_opt['fields'] as $field => $options)
            {

                if ( isset ($options[ 'filter' ] ) && $options[ 'filter' ] )
                {

                    if ( isset($options[ 'type' ]) )
                    {
                        switch ( $options[ 'type' ] )
                        {
                            case 'datetime':
                            case 'date':
                                
                                $d  = $this->_io->get($field.'_d');
                                $h  = $this->_io->get($field.'_h');
                                
                                if ($d && $h)
                                    $value = " between '{$d}' and date_add('{$h}',INTERVAL 1 DAY) ";
                                else
                                    if ($d)
                                        $value = " > '{$d}' ";
                                        else if ($h)
                                            $value = " < '{$h}' ";
                                if ($value)
                                    array_push($res, $field . $value);

                                break;
                            case 'text':
                                if ( $this->_io->get($field) )
                                    array_push($res, $field . " = '{$this->_io->get($field)}' ");
                                
                                break;
                            case 'gender':
                            case 'state':
                            default :
                                if ( $this->_io->get($field) )
                                    array_push($res, $field . " = '{$this->_io->get($field)}' ");
                                break;
                        }
                    }else {
                        if ( $this->_io->get($field) )
                            array_push($res, $field . " like '%{$this->_io->get($field)}%' ");
                    }
                }
            }

        }
        
        if (count($res) > 0)
            return implode ("AND ",$res);
        else
            return "";
    }

    public function __construct( $options = array() ) {

        $this->_io = new Ftl_IOHelper();
        $this->_io->addFromArray($_REQUEST);
        

        if ( isset( $options['orderFieldIgnore'] ) )
                $this->_opt['orderFieldIgnore'] .= $options['orderFieldIgnore'];

        $this->_opt = Ftl_ArrayUtil::merge($this->_opt,$options);

        //var_dump($this->_opt['fields']);

        $this->_opt[ 'orderFieldIgnore' ] = explode(',', $this->_opt[ 'orderFieldIgnore' ]);

        $this->_states[ $this->_opt['stateEnabledValue'] ]       = 'Habilitado';
        $this->_states[ $this->_opt['stateDisabledValue'] ]      = 'Inabilitado';
        $this->_states[ $this->_opt['stateUnmoderatedValue'] ]   = 'Sin moderar';


        $this->_opt['currentPage'] = $this->_io->getEscaped('page',1);

        if ( count($this->_opt['extendedActions']) > 0 )
        {
            $aux = "";
            foreach ( $this->_opt['extendedActions'] as $action => $options )
            {
                $aux .= "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"{$options[ 'title' ]}\"><a href=\"" .($options[ 'url' ] ? $options[ 'url' ] : Ftl_Path::getFileName()) . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,id,encrypt',false) ."&amp;action={$action}&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=:id\" accion=\"{$options[ 'title' ]}\" id=\"{$action}Row_:id\" title=\"{$options[ 'title' ]}\" ><span class=\"ui-icon {$options[ 'ui_icon' ]}\"></span></a></li>\n";
            }
            $this->_extendedActions = $aux;

        }

        $this->generateOrder();

    }




    public function show($data)
    {
        $this->_numColumns = 0;

        
        

        $html = "<table border=\"0\" width=\"100%\"  cellpadding=\"0\" cellspacing=\"0\" id=\"product-table\">\n";


        if ( count ( $this->_opt[ 'fields' ] ) > 0 )
        {
            $this->_numColumns = count ( $this->_opt[ 'fields' ] );



            $html.= "<tr>\n";

            if ( $this->_opt[ 'toggleAll' ] )
            {
                $this->_numColumns += 1;
                $this->_jqueryOnLoad['toogle'] = "  $('#chkAll').change(function (){\n
                                                        $('input[name=chkRow]').attr('checked', $(this).is(':checked'));\n
                                                    });\n";
                $html.= "<th class=\"table-header-check\"><input id=\"chkAll\" name=\"chkAll\" type=\"checkbox\"/></th>\n";
                
            }

            $html.= $this->parseHeaderColumn();

            if ( $this->_opt[ 'showActions' ])
            {
                $this->_numColumns += 1;
                $this->_jqueryOnLoad['tooltip'] = "UI.tooltip('li.info-tooltip');\n";
                $html.= "<th class=\"table-header-options line-left\"><span>Opciones</span></th>\n";
            }
            
            $html.= "</tr>\n";

        }

        if ($data === NULL)
        {
            $html.= '<tr><td colspan="' . $this->_numColumns . '" style="text-align:center"> No se encontraron resultados </td></tr>';
        }
        else
        {
            if (isset($data[0]['total']))
                $this->setTotalResults ($data[0]['total']);
            
            $identifier = 0;
            foreach ( $data as $i => $cols )
            {

                $identifier = (($this->_opt[ 'encryptFieldId' ]) ? md5($cols[$this->_opt[ 'fieldId' ]]) : $cols[$this->_opt[ 'fieldId' ]]);

                $html .= "<tr " . ($i % 2 == 0 ? "" : "class=\"alternate-row\"") . ">\n";

                if ( $this->_opt[ 'toggleAll' ] )
                {
                    $html.= "<td><input id=\"chkRow_{$identifier}\" name=\"chkRow\"  type=\"checkbox\"/></td>\n";
                }

                foreach( $this->_opt [ 'fields' ] as $field => $options )
                {
                    $html.= $this->parseDataColumn($field, $cols[$field]);
                }

                $html .= $this->parseOptionsColumn($cols);
                $html .= "</tr>\n";
            }
            
        }
        
        $html.= '</table>';
        $html .= $this->drawFooter();

        if ($this->_numfilters > 0){
            echo "<form id=\"mainform\" name=\"mainform\" method=\"GET\" action=\"". Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, implode(',',$this->_filtersNames),false) . "\"><input type=\"hidden\" name=\"orderBy\" value=\"".$this->_io->get('orderBy')."\" />\n<div id=\"accordion\"><h3><a href=\"javascript:void(0);\">Filtros</a></h3><div><table class=\"tbl-filtros\">" . str_replace ("numfilters", $this->_numfilters, $this->_htmlFilter) . "</form>\n";
            $this->_jqueryOnLoad["accordion"] = "$( \"#accordion\" ).accordion({collapsible: true,active:-1});\n";
        }
        if (count( $this->_jqueryOnLoad ) > 0 )
        {
            $html .= "<script type=\"text/javascript\">\n";
            $html .= "$(document).ready(function (){\n";

            foreach ($this->_jqueryOnLoad as $k=>$v)
            {
                $html .= $v . "\n";
            }
            $html .= "});\n";
            $html .= "</script>\n";
        }

        echo $html;

    }

    private function drawFooter ()
    {
        //$aux = "<tfoot><tr><td colspan=\"{$this->_numColumns}\" class=\"foot\">\n";

        $aux = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" id=\"paging-table\"><tr>";

        if ($this->_opt['toggleAll'])
        {
            /*$aux.="<td><div id=\"actions-box\">\n
				<a class=\"action-slider\" href=\"javascript:void(0);\"></a>\n
				<div id=\"actions-box-slider\">\n
					<a class=\"action-edit\" href=\"\">Edit</a>\n
					<a class=\"action-delete\" href=\"javascript:void(0);\">Delete</a>\n
				</div>\n
				<div class=\"clear\"></div>\n
			</div></td>\n";*/
        }
        
        $aux.="<td>{$this->_opt['totalResults']} registro/s encontrado/s</td>\n";
        if ($this->_opt [ 'usingPaginator' ])
        {
            $this->_opt['totalPages'] = ceil ( $this->_opt['totalResults'] / $this->_opt['resPerPage'] );

            $currentPage    = $this->_opt['currentPage'];
            $totalPages     = $this->_opt['totalPages'];

            $aux .= "<td>\n";

            $first  = ( $totalPages > 1 && $currentPage > 1  ) ? '<a class="page-far-left" href="' . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'page',false) . '&amp;page=1"></a>':'<div class="page-far-left"></div>';
            $ant    = ( $totalPages > 1 && $currentPage > 1  ) ? '<a class="page-left" href="'. Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'page',false) . '&amp;page=' . ($currentPage - 1) .'"></a>':'<div class="page-left"></div>';
            $sig    = ( $totalPages > 1 && $currentPage < $totalPages  ) ? '<a class="page-right" href="'. Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'page',false) . '&amp;page=' . ($currentPage + 1) .'"></a>' : '<div class="page-right"></div>';
            $last   = ( $totalPages > 1 && $currentPage < $totalPages  ) ? '<a class="page-far-right" href="'. Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'page',false) . '&amp;page=' . ($totalPages) .'"></a>' : '<div class="page-far-right"></div>';

            $aux .= $first.$ant."\n";
            $aux .= "&nbsp;<select onchange=\"javascript:document.location='". Ftl_Path::getFileName() . "?" . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'page',false) . "&amp;page=' + $('#cmbPaginas').val();\" id=\"cmbPaginas\" style=\"float:left;margin-left: 4px;margin-right: 2px;margin-top: 1px;\">";

            for($i=1 ; $i <= $totalPages; $i++)
            {
                $aux .= "<option value=\"$i\" ". ($i==$currentPage ? "selected" : "") .">$i</option>\n";
            }
            $aux .= "</select>\n";
            $aux .= $sig.$last."\n";
            $aux .= "</td>\n";

        }

        
        $aux.="</tr></table>\n";

        return $aux;

    }

    private function parseHeaderColumn(  )
    {

        $aux            = '';
        $filterType     = '';

        foreach ( $this->_opt [ 'fields' ] as $field => $options )
        {
            $cssSpanTitle   = '';
            $imgOrdesAsc    = '';
            $imgOrdesDesc   = '';

            

            if ($this->_opt['canOrder'] && !in_array($field, $this->_opt['orderFieldIgnore']))
            {
                $cssSpanTitle   = '';
                $imgOrdesAsc    = ( array_key_exists($field, $this->_mapOrder) && strtolower($this->_mapOrder[ $field ]) == 'asc' ) ? '<img src="images/table/order-selected-asc.png"/>' : '<img src="images/table/order-asc.png"/>';
                $imgOrdesAsc    = '<a href="' . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'orderBy',false) . $this->getOrderByForParam($field, 'ASC') . '">' . $imgOrdesAsc . '</a>';
                
                $imgOrdesDesc   = ( array_key_exists($field, $this->_mapOrder) && strtolower($this->_mapOrder[ $field ]) == 'desc' ) ? '<img src="images/table/order-selected-desc.png"/>': '<img src="images/table/order-desc.png"/>';
                $imgOrdesDesc    = '<a href="' . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'orderBy',false) . $this->getOrderByForParam($field, 'DESC') . '">' . $imgOrdesDesc . '</a>';

            }

            $aux .= "<th class=\"table-header-repeat line-left\"><span " . $cssSpanTitle . ">" . $options['title'] . "</span>" . $imgOrdesAsc . $imgOrdesDesc . "</th>\n";

            if ( isset ($options[ 'filter' ] ) && $options[ 'filter' ] )
            {
                $this->_numfilters += 1;
                
                $this->_htmlFilter .= "<tr><td style=\"min-width:100px;\"><span>{$options['title']}</span></td><td>";

                if ( isset($options[ 'type' ]) )
                {
                    switch ( $options[ 'type' ] )
                    {
                        case 'gender':
                            $this->_htmlFilter .= "<select id=\"$field\" name=\"$field\" class=\"input-text ui-widget ui-corner-all\"><option value=\"\">--</option>\n";
                            foreach($this->_gender as $k => $v)
                            {
                                $this->_htmlFilter .= "<option value=\"$k\" ". ($this->_io->get($field) == $k ? "selected" : "") . ">$v</option>\n";
                            }
                            $this->_htmlFilter .= "</select>";
                            array_push($this->_filtersNames, $field);
                            break;
                        case 'datetime':
                        case 'date':
                            $this->_htmlFilter .= "<input type=\"text\" name=\"{$field}_d\" value=\"{$this->_io->get($field.'_d')}\" class=\"input-text ui-widget ui-corner-all datepicker\" /> a <input type=\"text\" name=\"{$field}_h\" value=\"{$this->_io->get($field.'_h')}\" class=\"input-text ui-widget ui-corner-all datepicker\" />\n";
                            $this->_jqueryOnLoad["datepicker"] = "$( \".datepicker\" ).datepicker({dateFormat: 'yy-mm-dd'});";
                            array_push($this->_filtersNames, $field.'_d');
                            array_push($this->_filtersNames, $field.'_h');

                            break;
                        case "state":
                            $this->_htmlFilter .= "<select id=\"$field\" name=\"$field\" class=\"input-text ui-widget ui-corner-all\"><option value=\"\" ". ($this->_io->get($field,2) == $k ? "selected" : "") . ">--</option>\n";
                            foreach($this->_states as $k => $v)
                            {
                                $this->_htmlFilter .= "<option value=\"$k\" ". ($this->_io->get($field) != "" && $this->_io->get($field)     == $k ? "selected" : "") . ">$v</option>\n";
                            }
                            $this->_htmlFilter .= "</select>";
                            array_push($this->_filtersNames, $field);
                            break;
                        case "assoc":
                            
							$this->_htmlFilter .= "<select id=\"$field\" name=\"$field\" class=\"input-text ui-widget ui-corner-all\"><option value=\"\" ". ($this->_io->get($field,'') == '' ? "selected" : "") . ">--</option>\n";
                            
							if (isset($options[ 'data' ]) && is_array($options[ 'data' ])){
							
								foreach($options[ 'data' ] as $k => $v)
								{
									$this->_htmlFilter .= "<option value=\"$k\" ". ($this->_io->get($field) != "" && $this->_io->get($field)     == $k ? "selected" : "") . ">$v</option>\n";
								}

							}
                            $this->_htmlFilter .= "</select>";
                            array_push($this->_filtersNames, $field);
                            break;							
                        default :
                            $this->_htmlFilter .= "<input type=\"text\" id=\"$field\" name=\"$field\" class=\"input-text ui-widget ui-corner-all\" value=\"{$this->_io->get($field)}\"/>\n";
                            array_push($this->_filtersNames, $field);
                            break;
                    }
                }else {
                    $this->_htmlFilter .= "<input type=\"text\" id=\"$field\" name=\"$field\" class=\"input-text ui-widget ui-corner-all\" value=\"{$this->_io->get($field)}\"/>\n";
                    array_push($this->_filtersNames, $field);
                }
                if ($this->_numfilters == 1){
                    $this->_htmlFilter .= "</td><td rowspan=\"numfilters\" class=\"tdBuscar\"><a id=\"\" href=\"javascript:void(0);\" onclick=\"document.mainform.submit();\" ><img src=\"images/shared/btn_filtrar.png\"/></a></td></tr>";
                }else {
                    $this->_htmlFilter .= "</td></tr>";
                }

                
            }

        }

        $this->_htmlFilter .= "</table></div></div>";

        return $aux;
        
    }

    private function parseDataColumn ( $key , $value )
    {
        $aux    = $value;
        $fields = $this->_opt['fields'];
        if (array_key_exists($key, $fields))
        {
            if (isset($fields[$key]['type']))
            {
                
                switch($fields[$key]['type'])
                {
                    case "gender":
                        if (!is_null($aux))
                        {
                            $gender = (isset($fields[$key]['values'])) ? $fields[$key]['values'] : $this->_gender;
                            $aux    = (isset($gender[$aux])) ? $gender[$aux] : $aux;
                        }
                        break;
                    case "datetime":
                        if (!is_null($aux))
                        {
                            $format = ( isset( $fields[$key]['format'] ) ? $fields[$key]['format'] : self::DATETIME_FORMAT );
                            $aux = date( $format, strtotime( $aux ) );
                        }
                        break;
                    case "date":
                        if (!is_null($aux))
                        {
                            $format = ( isset( $fields[$key]['format'] ) ? $fields[$key]['format'] : self::DATE_FORMAT );
                            $aux = date( $format, strtotime( $aux ) );
                        }
                        break;
                    case "image":
                        if (!is_null($aux))
                        {
                            $width  = (isset($fields[$key]['width'])) ? $fields[$key]['width'] : self::IMAGE_WIDTH;
                            $height = (isset($fields[$key]['height'])) ? $fields[$key]['height'] : self::IMAGE_HEIGHT;
                            $folder = (isset($fields[$key]['folder'])) ? $fields[$key]['folder'] : '';

                            $aux    = "<a href=\"{$folder}{$aux}\" target=\"_blank\"><img border=0 width=$width height=$height src=\"{$folder}{$aux}\"/></a>";

                        }
                        break;
                    case "file":
                        if (!is_null($aux))
                        {
                            $folder = (isset($fields[$key]['folder'])) ? $fields[$key]['folder'] : '';
                            $aux    = "<a href=\"{$folder}{$aux}\" target=\"_blank\">{$aux}</a>";
                        }
                        break;
                    case "state":

                        if (!is_null($aux))
                        {
                            $state  = (isset($fields[$key]['values'])) ? $fields[$key]['values'] : $this->_states;
                            
                            $aux    = (isset($state[$aux])) ? $state[$aux] : $aux;
                        }

                        break;
                    case "assoc":

                        if (!is_null($aux))
                        {
                            if (isset($fields[$key]['data']) && is_array($fields[$key]['data']))
                            {
                                $aux = (isset($fields[$key]['data'][$value]) ? $fields[$key]['data'][$value] : $value);
                            }
							else
								$aux    = $value;
                        }

                        break;						
                    default:
                        if (!is_null($aux))
                        {
                            if (isset($fields[$key]['size']))
                            {
                                $aux = substr($aux, 0, $fields[$key]['size']);
                            }
                        }
                        break;

                        
                }
                
            }

            return "<td>{$aux}</td>\n";
        }

        return "";
    }

    private function parseOptionsColumn ($value)
    {
        $aux = "";
        

        if  ( $this->_opt['showActions'] )
        {
            $aux.= "<td class=\"options-width\">\n";
            $aux.= "<ul id=\"icons\" class=\"ui-widget ui-helper-clearfix\">";
            $aux.= ($this->_opt['canEdit'])             ? "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Editar\"><a href=\"" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id,encrypt',false) ."&amp;action=edit&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."\" accion=\"edit\" id=\"editRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) . "\" title=\"Editar\" ><span class=\"ui-icon ui-icon-pencil\"></span></a></li>" : "";
            
            $aux.= ($this->_opt['canDelete'])           ? "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Eliminar\"><a href=\"javascript:void(0);\" accion=\"delete\" id=\"editRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) . "\" title=\"Eliminar\" class=\"info-tooltip\" onclick=\"javascript:if (confirm('Deséa eliminar el registro?')) document.location = '" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id',false) ."&amp;action=delete&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."';\"><span class=\"ui-icon ui-icon-trash\"></span></a></li>" : "";

            if ($this->_opt['hasStatus'])
            {

                if ($this->_opt['canChangeStatus'] )
                {
                    
                        if ($value[$this->_opt['fieldStatus']] == $this->_opt['stateUnmoderatedValue'])
                        {
                            $aux.= "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Cambiar estado a {$this->_states[$this->_opt['stateEnabledValue']]}\"><a href=\"javascript:void(0);\" id=\"changeRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) . "|{$this->_opt['stateEnabledValue']}\"   onclick=\"javascript:if (confirm('Deséa cambiar el estado del registro a {$this->_states[$this->_opt['stateEnabledValue']]}?')) document.location = '" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id,encrypt',false) ."&amp;action=changeStatus&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."&amp;status=" . $this->_opt['stateEnabledValue'] . "';\"><span class=\"ui-icon ui-icon-check\"></span></a></li>\n";
                            $aux.= "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Cambiar estado a {$this->_states[$this->_opt['stateDisabledValue']]}\"><a href=\"javascript:void(0);\" id=\"changeRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) . "|{$this->_opt['stateDisabledValue']}\"  onclick=\"javascript:if (confirm('Deséa cambiar el estado del registro a {$this->_states[$this->_opt['stateDisabledValue']]}?')) document.location = '" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id,encrypt',false) ."&amp;action=changeStatus&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."&amp;status=" . $this->_opt['stateDisabledValue'] . "';\"><span class=\"ui-icon ui-icon-closethick\"></span></a></li>";
                        }
                        else if ($value[$this->_opt['fieldStatus']] == $this->_opt['stateEnabledValue'])
                        {
                            $aux.= "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Cambiar estado a {$this->_states[$this->_opt['stateDisabledValue']]}\"><a href=\"javascript:void(0);\" id=\"changeRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) . "|{$this->_opt['stateDisabledValue']}\"  onclick=\"javascript:if (confirm('Deséa cambiar el estado del registro a {$this->_states[$this->_opt['stateDisabledValue']]}?')) document.location = '" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id,encrypt',false) ."&amp;action=changeStatus&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."&amp;status=" . $this->_opt['stateDisabledValue'] . "';\"><span class=\"ui-icon ui-icon-closethick\"></span></a></li>";
                        }
                        else
                        {

                            $aux.= "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Cambiar estado a {$this->_states[$this->_opt['stateEnabledValue']]}\"><a href=\"javascript:void(0);\" id=\"changeRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."|{$this->_opt['stateEnabledValue']}\"   onclick=\"javascript:if (confirm('Deséa cambiar el estado del registro a {$this->_states[$this->_opt['stateEnabledValue']]}?')) document.location = '" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id,encrypt',false) ."&amp;action=changeStatus&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."&amp;status=" . $this->_opt['stateEnabledValue'] . "';\"><span class=\"ui-icon ui-icon-check\"></span></a></li>\n";
                        }
                }
                else
                {
                        if ($value[$this->_opt['fieldStatus']] == $this->_opt['stateUnmoderatedValue'])
                        {
                            $aux.= "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Cambiar estado a {$this->_states[$this->_opt['stateEnabledValue']]}\"><a href=\"javascript:void(0);\" id=\"changeRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) . "|{$this->_opt['stateEnabledValue']}\" onclick=\"javascript:if (confirm('Deséa cambiar el estado del registro a {$this->_states[$this->_opt['stateEnabledValue']]}?')) document.location = '" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id,encrypt',false) ."&amp;action=changeStatus&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."&amp;status=" . $this->_opt['stateEnabledValue'] . "';\"><span class=\"ui-icon ui-icon-check\"></span></a></li>\n";
                            $aux.= "<li class=\"ui-state-default ui-corner-all info-tooltip\" title=\"Cambiar estado a {$this->_states[$this->_opt['stateDisabledValue']]}\"><a href=\"javascript:void(0);\" id=\"changeRow_" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) . "|{$this->_opt['stateDisabledValue']}\" onclick=\"javascript:if (confirm('Deséa cambiar el estado del registro a {$this->_states[$this->_opt['stateDisabledValue']]}?')) document.location = '" . Ftl_Path::getFileName() . '?' . Ftl_ArrayUtil::toQueryString($this->_io->getAll(), true, 'action,status,id,encrypt',false) ."&amp;action=changeStatus&amp;encrypt=" . (($this->_opt['encryptFieldId']) ? "1" : "0") . "&amp;id=" . (($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']]) ."&amp;status=" . $this->_opt['stateDisabledValue'] . "';\"><span class=\"ui-icon ui-icon-closethick\"></span></a></li>";
                        }

                }


            }

            $aux.= Ftl_StringUtil::replaceVars($this->_extendedActions, array('id'=>(($this->_opt['encryptFieldId']) ? md5($value[$this->_opt['fieldId']]) : $value[$this->_opt['fieldId']])));
            //$aux.= ($this->_opt['canChangeStatus'])     ? "<a href=\"javascript:void(0);\" accion=\"changeStatus\" id=\"changeStatusRow_{$value[$this->_opt['fieldId']]}\" title=\"Cambiar estado\" class=\"icon-1 info-tooltip\"></a>" : "";
            $aux.= "</ul></td>\n";
        }

        return $aux;
    }

    private function generateOrder ()
    {
        if ($this->_opt['canOrder'] || $this->_opt['orderBy'])
        {
            
            $orderBy   = explode ( ',' , $this->_io->get('orderBy', $this->_opt['orderBy'] ) );
            foreach ( $orderBy as $order )
            {
                $order = explode( '|', $order);

                if ( count($order) == 2 && !in_array($order[0], $this->_opt[ 'orderFieldIgnore' ]) )
                {
                    $this->_mapOrder[ $order[0] ] = $order[1];
                }
            }
        }
    }

    private function getOrderByForParam ( $field = null , $dir = null )
    {

        $aux = $this->_mapOrder;
        
        if ( $field && $dir )
        {
            if ( array_key_exists( $field , $aux ) )
            {
                if ( $aux[$field] == $dir )
                    unset ( $aux[$field] );
                else
                    $aux[$field] = $dir;
            }
            else
                $aux[$field] = $dir;
        }

        $str = "";
        foreach ( $aux as $k => $v )
        {
            $str .= $k . '|' . $v . ',';
        }

        return ( count ( $aux ) > 0 ) ? "&amp;orderBy=". substr($str, 0, strlen($str)-1) : "";
    }

}
?>
